<script setup>
import { ref, onMounted } from 'vue'
import useUserInfoStore from '@/stores/userInfo.js'
import { useTokenStore } from '@/stores/token.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getWorkRecordsByDispatchId, 
  updateRepairRecordById, 
  getRepairRecordById, 
  getRepairRecordPage, 
  verifyRepairRecord 
} from '@/api/repairRecord.js';
import WorkOrderDetail from './WorkOrderDetail.vue'

const uploadRef = ref()
const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()
const router = useRouter()

// 列表的物品总数
const itemsTotal = ref(1)

// 设备分页查询的表单结构
const repairRecordPageQueryData = ref({
  page: 1,
  pageSize: 5,
  id: null,
  deviceId: null,
  type: null,
  status: null,
})

const repairRecords = ref([])

// 在组件挂载时获取区域数据
onMounted(() => {
  getRepairRecords()
})

// 分页查询获取设备列表
const getRepairRecords = async () => {
  let result = await getRepairRecordPage(repairRecordPageQueryData.value)
  repairRecords.value = result.records
  itemsTotal.value = result.total
}

// 页面加载时获取一次所有设备
getRepairRecords()

// 分页大小改变时重新分页查询
const handleSizeChange = (val) => {
  repairRecordPageQueryData.value.pageSize = val
  getRepairRecords()
}

// 分页页码改变时重新分页查询
const handleCurrentChange = (val) => {
  repairRecordPageQueryData.value.page = val
  getRepairRecords()
}

// 是否在编辑设备，若为true则呼出右侧编辑窗口
const isEditing = ref(false)
// 当前设备，用于承载编辑设备与添加设备的表单
const currentRepairRecord = ref({})

const updateRepairRecordInfo = async () => {
  // 调用接口
  let result = await updateRepairRecordById(currentRepairRecord.value.id, currentRepairRecord.value)
  ElMessage.success(result.msg ? result.msg : '修改成功')
}

// 图片上传成功的回调函数
const uploadSuccess = (result) => {
  currentRepairRecord.value.image = result.data
}

// 查看设备详情
const isViewing = ref(false)
const viewRepairRecord = async (row) => {
  isViewing.value = true
  currentRepairRecord.value = row
}

// 编辑设备
const editRepairRecord = async (row) => {
  isEditing.value = true
  let result = await getRepairRecordById(row.id)
  currentRepairRecord.value = result.data
}

// 取消编辑
const cancelClickEditing = () => {
  isEditing.value = false
}

// 提交编辑
const confirmClickEditing = () => {
  updateRepairRecordInfo()
  isEditing.value = false
  getRepairRecords()
}

// 新增方法：根据派单ID获取从属工单ID
const workRecords = ref([])
const getWorkRecords = async (dispatchId) => {
  try {
    let result = await getWorkRecordsByDispatchId(dispatchId)
    workRecords.value = result.data
    ElMessageBox.alert(JSON.stringify(workRecords.value, null, 2), '从属工单ID', {
      confirmButtonText: '确定',
    }).then(() => {
      // 显示工单详情
      router.push({
        name: 'WorkOrderDetail',
        params: { workOrderData: workRecords.value[0] }
      })
    })
  } catch (error) {
    ElMessage.error('获取从属工单ID失败')
  }
}

// 新增方法：完成某一报修记录审核
const verifyRepair = async (id, isApproved) => {
  try {
    let result = await verifyRepairRecord(id, isApproved)
    ElMessage.success(result.msg ? result.msg : '审核成功')
    getRepairRecords()
  } catch (error) {
    ElMessage.error('审核失败')
  }
}
</script><template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>报修记录管理</span>
      </div>
    </template>

    <div>
      <!-- 顶部栏，包含分页查询过滤条件 -->
      <el-form class="search-filter" :model="repairRecordPageQueryData">
        <el-form-item label="设备编号">
          <el-input v-model="repairRecordPageQueryData.id" type="text"></el-input>
        </el-form-item>
        <el-form-item label="维修类型">
          <el-input v-model="repairRecordPageQueryData.type" type="text"></el-input>
        </el-form-item>
        <el-form-item label="记录状态">
          <el-input v-model="repairRecordPageQueryData.status" type="text"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRepairRecords">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <hr style="background-color: #eee; height: 1px; border: none;" />

    <!-- 报修记录表格 -->
    <el-table :data="repairRecords" style="width: 100%">
      <el-table-column prop="id" label="设备编号" width="180" sortable />
      <el-table-column prop="deviceId" label="设备ID" width="180" sortable />
      <el-table-column prop="description" label="评价" />
      <el-table-column prop="repairTypeId" label="维修类型ID" />
      <el-table-column prop="workOrderId" label="工单ID" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateTime" label="最后修改时间" />
      <el-table-column prop="operations" label="操作" fixed="right">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="viewRepairRecord(scope.row)">详情</el-button>
          <el-button link type="primary" size="small" @click="editRepairRecord(scope.row)">编辑</el-button>
          <el-button link type="primary" size="small" @click="getWorkRecords(scope.row.workOrderId)">从属工单</el-button>
          <el-button link type="primary" size="small" @click="verifyRepair(scope.row.id, 'yes')">审核通过</el-button>
          <el-button link type="primary" size="small" @click="verifyRepair(scope.row.id, 'no')">审核不通过</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 页码切换组件 -->
    <div class="pagination-block">
      <el-pagination
        layout="prev, pager, next, sizes"
        :total="itemsTotal"
        :page-size="repairRecordPageQueryData.pageSize"
        v-model:current-page="repairRecordPageQueryData.page"
        v-model:page-size="repairRecordPageQueryData.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 查看报修记录详情的弹窗 -->
  <el-dialog v-model="isViewing" title="报修记录详情" width="80%" fullscreen destroy-on-close center>
    <RepairRecordDetail :repairRecordData="currentRepairRecord" />
  </el-dialog>

  <!-- 编辑报修记录的侧边界面 -->
  <el-drawer v-model="isEditing" :direction="rtl" size="50%">
    <template #header>
      <h4>编辑 {{ currentRepairRecord.id }} 信息</h4>
    </template>
    <template #default>
      <div class="form-edit-repairRecord">
        <el-row>
          <el-col :span="18">
            <el-form :model="currentRepairRecord" :rules="rules" label-width="150px" size="large">
              <el-form-item label="设备编号" prop="deviceId">
                <el-input v-model="currentRepairRecord.deviceId"></el-input>
              </el-form-item>
              <el-form-item label="评价" prop="description">
                <el-input v-model="currentRepairRecord.description"></el-input>
              </el-form-item>
              <el-form-item label="维修类型ID" prop="repairTypeId">
                <el-input v-model="currentRepairRecord.repairTypeId"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClickEditing">取消</el-button>
        <el-button type="primary" @click="confirmClickEditing">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped>
.search-filter {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.pagination-block {
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-edit-device {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>
